package com.ctrl.riveradministrator.mvp.view.activity.trace;

import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.ctrl.riveradministrator.R;
import com.ctrl.riveradministrator.common.Constants;
import com.ctrl.riveradministrator.MainActivity;
import com.ctrl.riveradministrator.mvp.view.activity.trace.daemon.DaemonManager;
import com.ctrl.riveradministrator.mvp.view.activity.trace.daemon.DaemonReceiver;

import static android.app.Notification.DEFAULT_ALL;

public class TraceService extends Service implements DaemonReceiver.ScreenStateListener {

    public static final String START_TRACE_SERVICE = "START_TRACE_SERVICE";
    public static final String STOP_TRACE_SERVICE = "STOP_TRACE_SERVICE";

    // Baidu定位相关
    public LocationClient mLocationClient = null;
    private LocationClientOption clientOption = null;
    private BaiduLocationListener locationListener = null;
    private String[] locs = {"0", "0", "未定位"}; // Baidu地图中传递监听位置数据，locs[0]纬度、locs[1]经度、locs[2]详细地址

    // Notification相关
    private NotificationManager manager;
    private NotificationCompat.Builder builder;
    private NotificationChannel channel;

    // 存储相关
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    //保活相关
    private DaemonReceiver daemonReceiver;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @SuppressLint("CommitPrefEdits")
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TraceService", "onCreate");
        daemonReceiver = new DaemonReceiver(this);
        if(requirePermission()){
            DaemonManager.getInstance(this).createFloatView(this);
        }else{
            Toast.makeText(this, "权限授予失败，可能造成系统不稳定，请在设置中手动授权", Toast.LENGTH_LONG).show();
        }

        daemonReceiver.begin(this);//启动保活服务
        manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        // 判断系统是否为8.0
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            channel = new NotificationChannel("static", "Primary Channel", NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(this, "static");
        } else {
            builder = new NotificationCompat.Builder(this);
        }   
        builder.setContentTitle("巡检任务")
                .setContentText("正在进行巡检任务")
                .setPriority(NotificationCompat.PRIORITY_MAX)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setDefaults(DEFAULT_ALL)
                .setAutoCancel(false)
                .setOngoing(true);
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        sp = this.getSharedPreferences(Constants.TRACE_SP, MODE_PRIVATE);
        editor = sp.edit();
        try {
            location();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TraceService", "onDestroy");
        // 停止服务
        mLocationClient.stop();
        daemonReceiver.unregisterReceiver();
        manager.cancel(1);
    }

    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TraceService", "onStartCommand");
        String state;
        // 判断intent是否为空，如果为空则为上次异常退出service的记录
        if (intent == null) {
            state = sp.getString(Constants.TRACE_SERVICE_INTENT, START_TRACE_SERVICE);
        } else {
            state = intent.getAction();
        }
        switch (state) {
            case START_TRACE_SERVICE:
                // 开启服务
                if (!mLocationClient.isStarted()) {
                    mLocationClient.start();
                    manager.notify(1, builder.build());
                }
                editor.putString(Constants.TRACE_SERVICE_INTENT, START_TRACE_SERVICE);
                break;
            case STOP_TRACE_SERVICE:
                // 停止服务
                mLocationClient.stop();
                manager.cancel(1);
                editor.putString(Constants.TRACE_SERVICE_INTENT, STOP_TRACE_SERVICE);
                break;
        }
        editor.apply();
        return super.onStartCommand(intent, Service.START_REDELIVER_INTENT, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    /**
     * Baidu定位
     */
    private void location() throws Exception {
        mLocationClient = new LocationClient(this);
        locationListener = new BaiduLocationListener();
        mLocationClient.registerLocationListener(locationListener);
        clientOption = new LocationClientOption();
        clientOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        clientOption.setCoorType("bd09ll");
        clientOption.setEnableSimulateGps(true);
        //clientOption.setScanSpan(5*1000);
        clientOption.setOpenGps(true);
        clientOption.setLocationNotify(true);
        clientOption.setOpenAutoNotifyMode();
//        clientOption.setOpenAutoNotifyMode(6 * 1000, 30, LocationClientOption.LOC_SENSITIVITY_HIGHT);
        clientOption.setIgnoreKillProcess(true); // 默认在stop时不杀死进程
        clientOption.setIsNeedAddress(true);
        mLocationClient.setLocOption(clientOption);
    }

    @Override
    public void onScreenOn() {
        // 亮屏，finish一个像素的Activity
        DaemonManager.getInstance(TraceService.this)
                .finishKeepLiveActivity();
    }

    @Override
    public void onScreenOff() {
        // 灭屏，启动一个像素的Activity
        DaemonManager.getInstance(TraceService.this)
                .startKeepLiveActivity();
    }

    /**
     * 授予悬浮窗权限
     *
     * @return true 有权限
     */
    private boolean requirePermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (!Settings.canDrawOverlays(this)) {// 是否具有悬浮窗权限
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    public class BaiduLocationListener extends BDAbstractLocationListener {

        private TraceActivity.TraceHandler traceHandler = new TraceActivity.TraceHandler();
        private Message message = traceHandler.obtainMessage();
        private String[] locs = new String[3];
        private double latitude;
        private double longitude;
        private String addrStr;

        @Override
        public void onLocDiagnosticMessage(int i, int i1, String s) {
            super.onLocDiagnosticMessage(i, i1, s);
            Log.d("onLocDiagnosticMessage", "i:"+i+",+i1:"+i1+",s:"+s);
        }

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            latitude = bdLocation.getLatitude();    //获取纬度信息
            longitude = bdLocation.getLongitude();    //获取经度信息
            addrStr = bdLocation.getAddrStr(); //详细地址
            locs[0] = String.valueOf(latitude);
            locs[1] = String.valueOf(longitude);
            locs[2] = addrStr;
            message = traceHandler.obtainMessage();
            message.what = 0x19;
            message.obj = locs;
            traceHandler.sendMessage(message);

            int locType = bdLocation.getLocType();
            int errorCode = bdLocation.getLocType(); //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明


            Log.d("cyc", "BaiduLocationListener ===> latitude:" + latitude + ";longitude:" + longitude +
                    ";errorCode:" + errorCode + ";addrStr:" + addrStr + ";locType:" + locType);
        }
    }
}
